import axios from 'axios';

/**
 *
 * @param config
 * [urlName,method,params,noLoading]
 * @param callback
 */
class network {
  constructor(baseURL, kkui) {
    this.baseURL = baseURL;
    this.kkui = kkui;
  };

  ajax(config, callback) {
    const axiosCfg = {
      "baseURL": this.baseURL,
      "headers": {
        "Content-Type": config.isFormData ? "application/x-www-form-urlencoded" : (config.isFormData2?'multipart/form-data':"application/json; charset=utf-8")
      },
      "setTimeout": 5000
    };

    const server = axios.create(axiosCfg);
    let cfg = {
      url: config.url,
      method: config.method || "post"
    };

    if (config.responseType) {
      cfg.responseType = config.responseType;
    }
    if (config.data) {
      cfg.data = config.isFormData ? config.data : JSON.stringify(config.data);
    }
    let loadingIdx = 0;
    server.interceptors.request.use(cfg => {
      const user = this.kkui.cache.get('user');
      user && user.token && (cfg.headers.Authorization = user.token);
      if (config.loading) {
        loadingIdx = this.kkui.loading.show();
      }
      return cfg;
    }, err => {
      this.kkui.msg({icon: 0, cont: JSON.stringify(err)});
      return err;
    });

    server.interceptors.response.use(rst => {
      this.kkui.loading.hide(loadingIdx);
      return rst.data;
    }, err => {
      let cont='';
      if(err.code === 'ERR_NETWORK'){
        cont='"服务未启动"或"网络不通"!<br>';
      }else if(err.code === 'ERR_BAD_RESPONSE'){
        cont='服务接口出错!<br>';
      }
      cont+= err.message;

      this.kkui.msg({
        icon: 0,
        title: '出错啦',
        cont: cont,
        time: 4000
      });
      // return err;
    });
    server(cfg).then(res => {
      if (res && typeof callback === "function") {
        callback(res);
      }
    }).catch(err => {
      if (typeof callback === "function") callback(err);
      throw err;
    });
  }
}

export default network;
